﻿using SelfMadeMillionaire.Core.Services;
using SelfMadeMillionaire.Web.Infrastructure.ViewModels.MailingList;
using System;
using System.Web;
using System.Web.Mvc;
using SelfMadeMillionaire.Core.Entities;
using SelfMadeMillionaire.Core;
using SelfMadeMillionaire.Core.Enums;

namespace SelfMadeMillionaire.Web.Infrastructure.Controllers
{
	public class MailingListController : BaseController
	{
        private readonly IMailingListService _mailingListService;
        private readonly ISubscriberService _subscriberService;
        private readonly IEmailService _emailService;
        private readonly IPromotionService _promotionService;
        private readonly ILogService _logService;

        public MailingListController(IMailingListService mailingListService, ISubscriberService subscriberService, IEmailService emailService, IPromotionService promotionService, ILogService logService)
		{
			_mailingListService = mailingListService;
			_subscriberService = subscriberService;
			_emailService = emailService;
            _promotionService = promotionService;
            _logService = logService;
		}

		[HttpGet]
		public ActionResult Subscribe(string mailing)
		{
			var model = new SubscribeViewModel { IsSMM = true};
            model.ProductType = CoreConstants.FREE_SUBSCRIPTION;
            model.SilverPrice = _subscriberService.GetSilverPricePackage();
            model.GoldPrice = _subscriberService.GetGoldPricePackage();
            model.PlatinumPrice = _subscriberService.GetPlatinumPricePackage();
            model.Mailing = mailing;

            if (!string.IsNullOrEmpty(mailing))
                _subscriberService.UpdateMODetail_SubscribeRedirect(mailing);

			return View(model);
		}

        [HttpGet]
        public ActionResult SubscribeFB()
        {
            var model = new SubscribeViewModel { IsSMM = true };
            model.ProductType = CoreConstants.FREE_SUBSCRIPTION;
            model.SilverPrice = _subscriberService.GetSilverPricePackage();
            model.GoldPrice = _subscriberService.GetGoldPricePackage();
            model.PlatinumPrice = _subscriberService.GetPlatinumPricePackage();

            if (Session["FB_Email"] != null)
                model.Email = Session["FB_Email"].ToString();
            if (Session["FB_FirstName"] != null)
                model.FirstName = Session["FB_FirstName"].ToString();
            if (Session["FB_LastName"] != null)
                model.LastName = Session["FB_LastName"].ToString();


            return View("Subscribe", model);
        }



		[HttpPost]
        public ActionResult Subscribe(SubscribeViewModel model)
		{
			if (ModelState.IsValid)
			{
                string message = "";

                // if promocode applied - check it once again and restore prices
                if (!string.IsNullOrEmpty(model.PromoCode))
                {
                    double priceSilver = _subscriberService.GetSilverPricePackage();
                    double priceGold = _subscriberService.GetGoldPricePackage();
                    double pricePlatinum = _subscriberService.GetPlatinumPricePackage();
                    GetPromoCodeData(model.PromoCode, out message, out priceSilver, out priceGold, out pricePlatinum);

                    model.SilverPrice = priceSilver;
                    model.GoldPrice = priceGold;
                    model.PlatinumPrice = pricePlatinum;
                }

				if (_subscriberService.IsExists(model.Email, 0))
				{
				    ModelState.AddModelError("Email", "This email is already used");
				}
				else
				{
                    // Create new subscriber
                    var subscriber = new Subscriber
					{
						ID = model.ID,
						FirstName = model.FirstName,
						LastName = model.LastName,
						Email = model.Email,
						ProductType = (byte) GetProductType(model.IsSMM, model.IsMMM),
						PasswordHash = PasswordUtility.GetPasswordHash(model.Password),
						//SubscriptionLevel = (byte?) model.SubscriptionLevel,
                        SubscriptionLevel = 0,
						Token = Guid.NewGuid(),
                        Status = (byte)StatusType.Active
					};
                    _subscriberService.Add(subscriber);

                    // if need pay - create order
                    if (model.ProductType != CoreConstants.FREE_SUBSCRIPTION)
                    {
                        // Create order with full price
                        Order order = _subscriberService.Order(model.Email, model.ProductType);

                        // if promocode applied recalc order
                        if (!string.IsNullOrEmpty(model.PromoCode))
                        {
                            if (string.IsNullOrEmpty(message))
                            {
                                order.PromoCode = model.PromoCode;
                                
                                if (model.ProductType == CoreConstants.UPGRADE_TO_SILVER_PRODUCT)
                                    order.Price = model.SilverPrice;
                                else if (model.ProductType == CoreConstants.UPGRADE_TO_GOLD_PRODUCT)
                                    order.Price = model.GoldPrice;
                                else if (model.ProductType == CoreConstants.UPGRADE_TO_PLATINUM_PRODUCT)
                                    order.Price =  model.PlatinumPrice;

                                order = _subscriberService.UpdateOrder(order);
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(model.Mailing))
                        _subscriberService.UpdateMODetail_SubscribeFinish(model.Mailing);

                    // auth user
                    Authenticate(model.Email, subscriber.FirstName, subscriber.LastName, subscriber.EndDate.HasValue ? subscriber.EndDate.Value : DateTime.Now.AddDays(7), ((int)GetUserRole(subscriber)).ToString(), true);

                    // if pay - redirect to pay
                    if (model.ProductType != CoreConstants.FREE_SUBSCRIPTION)
                    {
                        return RedirectToAction("GotoPayPal", "Profile");
                    }
                    // if free account - redirect to home
                    else
                    {
                        return RedirectToAction("Index", "Profile");
                    }
					
				}
			}

			return View(model);
		}

        [HttpPost]
        public ActionResult ApplyPromoCode(string promocode)
        {
            double priceSilver = _subscriberService.GetSilverPricePackage();
            double priceGold = _subscriberService.GetGoldPricePackage();
            double pricePlatinum = _subscriberService.GetPlatinumPricePackage();
            string message = String.Empty;

            GetPromoCodeData(promocode, out message, out priceSilver, out priceGold, out pricePlatinum);
            return Json(new { message, priceSilver, priceGold, pricePlatinum }, JsonRequestBehavior.AllowGet);
        }

        [NonAction]
        private void GetPromoCodeData(string promocode, out string message, out double priceSilver, out double priceGold, out double pricePlatinum)
        {
            priceSilver = _subscriberService.GetSilverPricePackage();
            priceGold = _subscriberService.GetGoldPricePackage();
            pricePlatinum = _subscriberService.GetPlatinumPricePackage();

            message = String.Empty;
            if (String.IsNullOrEmpty(promocode))
            {
                message = "Enter promocode, please";
                return;
            }

            Promotion promo = _promotionService.GetPromoByCode(promocode);
            if (promo == null)
            {
                message = "Code is not valid";
                return;
            }

            // Date validation
            DateTime dtToday = DateTime.Today.Date;
            if ((dtToday < promo.EffectiveDate) || (dtToday > promo.ExpirationDate))
            {
                message = "Code is not valid";
                return;
            }
            // Product validation
            switch ((PromotionProduct)promo.Product)
            {
                case PromotionProduct.Webinar:
                    message = "Code is not valid";
                    return;
                    break;
                case PromotionProduct.SubscriptionRenewal:
                    message = "Code is not valid";
                    return;
                    break;
                case PromotionProduct.AllSubscriptionLevels:
                    priceSilver = CalculateNewPrice(priceSilver, promo.Discount, promo.IsPercent);
                    priceGold = CalculateNewPrice(priceGold, promo.Discount, promo.IsPercent);
                    pricePlatinum = CalculateNewPrice(pricePlatinum, promo.Discount, promo.IsPercent);
                    break;
                case PromotionProduct.SilverSubscription:
                    priceSilver = CalculateNewPrice(priceSilver, promo.Discount, promo.IsPercent);
                    break;
                case PromotionProduct.GoldSubscription:
                    priceGold = CalculateNewPrice(priceGold, promo.Discount, promo.IsPercent);
                    break;
                case PromotionProduct.PlatinumSubscription:
                    priceGold = CalculateNewPrice(pricePlatinum, promo.Discount, promo.IsPercent);
                    break;
            }
        }

		[HttpGet]
		public ActionResult UnSubscribe()
		{
			return View(new UnsubscribeViewModel());
		}

		[HttpPost]
		public ActionResult UnSubscribe(UnsubscribeViewModel model)
		{
			model.IsSuccess = false;

			if (ModelState.IsValid)
			{
				if (_subscriberService.IsExists(model.Email, 0))
				{
					_mailingListService.Unsubscribe(model.Email);
					model.IsSuccess = true;
				}
				else
				{
					ModelState.AddModelError("Email", "Email doesn't exists");
				}
			}

			return View(model);
		}
	}
}
